package com.example.shgt;

import android.annotation.SuppressLint;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MyPurchasesActivity extends AppCompatActivity {

    private RecyclerView recyclerView;
    private MyPurchasesAdapter adapter;
    private List<Purchase> purchaseList;
    private long userId; // 声明 userId 变量

    // 数据模型类
    public static class Purchase {
        private String id;
        private long goodsId;
        private double price;
        private String sellerName;
        private String goodsDescription;
        private String sellerAvatar;
        private long createTime; // 添加创建时间字段

        // Getters
        public String getId() { return id; }
        public long getGoodsId() { return goodsId; }
        public double getPrice() { return price; }
        public String getSellerName() { return sellerName; }
        public String getGoodsDescription() { return goodsDescription; }
        public String getSellerAvatar() { return sellerAvatar; }
        public long getCreateTime() { return createTime; } // 添加 getter
    }

    // 响应模型类
    public static class MyPurchasesResponse {
        private int code;
        private Data data;

        public static class Data {
            private List<Purchase> records;

            public List<Purchase> getRecords() { return records; }
        }

        public int getCode() { return code; }
        public Data getData() { return data; }
    }

    // 适配器类
    private class MyPurchasesAdapter extends RecyclerView.Adapter<MyPurchasesAdapter.ViewHolder> {
        private List<Purchase> purchases;

        public MyPurchasesAdapter(List<Purchase> purchases) {
            this.purchases = purchases;
        }

        public class ViewHolder extends RecyclerView.ViewHolder {
            public TextView sellerNameTextView, priceTextView, descriptionTextView, createTimeTextView; // 添加 createTimeTextView
            public ImageView sellerAvatarImageView;

            public ViewHolder(View view) {
                super(view);
                sellerNameTextView = view.findViewById(R.id.tv_seller_name);
                priceTextView = view.findViewById(R.id.tv_price);
                descriptionTextView = view.findViewById(R.id.tv_goods_description);
                createTimeTextView = view.findViewById(R.id.tv_create_time); // 初始化 createTimeTextView
                sellerAvatarImageView = view.findViewById(R.id.iv_seller_avatar);
            }
        }


        @Override
        public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = getLayoutInflater().inflate(R.layout.item_purchase, parent, false);
            return new ViewHolder(view);
        }

        @Override
        public void onBindViewHolder(ViewHolder holder, int position) {
            Purchase purchase = purchases.get(position);
            holder.sellerNameTextView.setText(purchase.getSellerName());
            holder.priceTextView.setText("¥" + purchase.getPrice());
            holder.descriptionTextView.setText(purchase.getGoodsDescription());

            // 格式化创建时间并显示
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
            String formattedDate = sdf.format(new Date(purchase.getCreateTime())); // 使用 getCreateTime
            holder.createTimeTextView.setText(formattedDate);

            Glide.with(holder.itemView.getContext()).load(purchase.getSellerAvatar()).into(holder.sellerAvatarImageView);
        }


        @Override
        public int getItemCount() {
            return purchases.size();
        }
    }

    @SuppressLint("MissingInflatedId")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_purchases);

        recyclerView = findViewById(R.id.rv_my_purchases);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        purchaseList = new ArrayList<>();
        adapter = new MyPurchasesAdapter(purchaseList);
        recyclerView.setAdapter(adapter);

        ImageView backButton = findViewById(R.id.iv_back);
        backButton.setOnClickListener(v -> finish());

        // 从 SharedPreferences 获取用户ID
        SharedPreferences sharedPreferences = getSharedPreferences("UserPrefs", MODE_PRIVATE);
        userId = Long.parseLong(sharedPreferences.getString("userId", "0")); // 获取并解析用户ID

        fetchMyPurchases(userId, 1, 10); // 请求第一页的购买记录
    }

    private void fetchMyPurchases(long userId, int currentPage, int pageSize) {
        String url = "https://api-store.openguet.cn/api/member/tran/trading/buy?userId=" + userId + "&current=" + currentPage + "&size=" + pageSize;

        OkHttpClient client = new OkHttpClient();

        Request request = new Request.Builder()
                .url(url)
                .addHeader("appId", "479dbe79299a4653ada0432942111871")
                .addHeader("appSecret", "14687c6d2cc860b264339b1d93bf409f2bb6c")
                .addHeader("Accept", "application/json, text/plain, */*")
                .addHeader("Content-Type", "application/json")
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("API Failure", e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    String responseData = response.body().string();
                    parseResponseData(responseData);
                } else {
                    Log.e("API Error", "Response code: " + response.code());
                }
            }
        });
    }

    private void parseResponseData(String jsonData) {
        MyPurchasesResponse response = new Gson().fromJson(jsonData, MyPurchasesResponse.class);
        if (response.getCode() == 200) {
            List<Purchase> records = response.getData().getRecords();
            runOnUiThread(() -> {
                purchaseList.clear();
                purchaseList.addAll(records);
                adapter.notifyDataSetChanged();
            });
        } else {
            // 处理错误信息
        }
    }
}
